package com.uqpsoftware.uqplist.tabs;

import static junit.framework.Assert.assertNotNull;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.uqpsoftware.uqplist.ActionBarTabs;
import com.uqpsoftware.uqplist.DataPersistence;
import com.uqpsoftware.uqplist.R;
import com.uqpsoftware.uqplist.tasks.Task;
import com.uqpsoftware.uqplist.tasks.TaskListAdapter;

public class TaskListFragment extends Fragment implements ListData {

	// components
	private Button mAddTaskButton;
	private EditText mTaskNameEditText;
	private ListView mTaskList;
	private Context mContext;
	private List<Task> mTasks;
	private TaskListAdapter mTaskListAdapter;
	private FragmentActivity mParentActivity;

	// the id to give to the next task
	private static int sNextID = 0;

	// the ID of this fragment
	private int mThisID;

	// persistence
	private DataPersistence mDataPersistence;

	// keys
	private static final String FRAGMENT_ID_KEY = ActionBarTabs.FRAGMENT_ID_KEY;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// setup some variables
		mContext = getActivity().getApplicationContext();
		mDataPersistence = DataPersistence.get(mContext);
		mTasks = new ArrayList<Task>();

		// set keyboard mode
		getActivity().getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		// grab the ID for this fragment
		Bundle arguments = getArguments();
		mThisID = Integer.parseInt(arguments.getString(FRAGMENT_ID_KEY));

		// give the activity a reference to this fragment
		mParentActivity = getActivity();
		ActionBarTabs activity = (ActionBarTabs) getActivity();
		activity.setFragmentToActivity(this, mThisID);

		// grab the id for the next task
		sNextID = mDataPersistence.getCurrentTaskID(mThisID);

		// populate tasks from persistence
		Set<String> taskIDs = mDataPersistence.getListOfCurrentTaskIDs(mThisID);
		for (String id : taskIDs) {
			Task persistedTask = mDataPersistence.getTask(Integer.parseInt(id));
			mTasks.add(persistedTask);
		}
		mTasks = sort(mTasks);
		mTasks = reverse(mTasks);

		// instantiate adapter and give it the data
		mTaskListAdapter = new TaskListAdapter(mContext, R.layout.task, mTasks);
		mTaskListAdapter.setListData(this);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		return inflater.inflate(R.layout.task_list, container, false);
	}

	public void refresh() {
		List<Task> tempList = new ArrayList<Task>(mTasks);
		for (Task t : tempList) {
			if (t.isCompleted()) {
				mTasks.remove(t);
				mDataPersistence.removeTask(t.getID());
			}
		}
		persistListOfCurrentTaskIDs();
		mTaskListAdapter.notifyDataSetChanged();

	}

	public void deleteTask(int taskID) {
		Task task = getTaskWithID(taskID);
		if (task == null) {
			return;
		}
		mTasks.remove(task);
		mDataPersistence.removeTask(task.getID());
		persistListOfCurrentTaskIDs();
		mTaskListAdapter.notifyDataSetChanged();
	}

	public void renameTask(int taskID, String name) {
		if ((name == null) || (name.equals(""))) {
			return;
		}
		Task task = getTaskWithID(taskID);
		if (task == null) {
			return;
		}
		task.setName(name);
		mDataPersistence.persistTask(task);
		mTaskListAdapter.notifyDataSetChanged();
	}

	public Integer getID() {
		return mThisID;
	}

	@Override
	public void onViewCreated(final View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);

		mTaskNameEditText = (EditText) view.findViewById(R.id.taskname);
		mTaskNameEditText
				.setOnEditorActionListener(new OnEditorActionListener() {

					@Override
					public boolean onEditorAction(TextView v, int actionId,
							KeyEvent event) {
						createNewTask();
						return true;
					}
				});
		mTaskList = (ListView) view.findViewById(R.id.taskslist);
		mTaskList.setAdapter(mTaskListAdapter);

		mAddTaskButton = (Button) view.findViewById(R.id.addtask);
		mAddTaskButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				createNewTask();
			}
		});
	}

	private void createNewTask() {
		String taskName = mTaskNameEditText.getText().toString();
		if (taskName.equals("")) {
			return;
		}
		mTaskNameEditText.setText("");
		Task newTask = new Task(taskName, sNextID);
		++sNextID;
		mTasks.add(newTask);
		mDataPersistence.persistTask(newTask);
		mDataPersistence.persistCurrentTaskID(mThisID, sNextID);
		persistListOfCurrentTaskIDs();
		mTaskListAdapter.notifyDataSetChanged();

		// move listview to the bottom
		mTaskList.post(new Runnable() {

			@Override
			public void run() {
				mTaskList.setSelection(mTaskList.getCount() - 1);

			}
		});
	}

	@Override
	public void setCompletedStatusOfTask(int ID) {
		Task taskWithChangedStatus = getTaskWithID(ID);
		assertNotNull(taskWithChangedStatus);
		if (taskWithChangedStatus == null) {
			return;
		}
		taskWithChangedStatus
				.setCompleted(!taskWithChangedStatus.isCompleted());
		mDataPersistence.persistTask(taskWithChangedStatus);
		mTaskListAdapter.notifyDataSetChanged();

	}

	private Task getTaskWithID(int ID) {
		for (Task task : mTasks) {
			if (task.getID() == ID) {
				return task;
			}
		}
		return null;
	}

	private void persistListOfCurrentTaskIDs() {
		Set<String> taskIDs = new HashSet<String>();
		for (Task task : mTasks) {
			taskIDs.add("" + task.getID());
		}
		mDataPersistence.persistListOfCurrentTaskIDs(mThisID, taskIDs);
	}

	private List<Task> sort(List<Task> originalList) {
		List<Task> sortedList = new ArrayList<Task>();
		int iterations = originalList.size();
		for (int i = 0; i < iterations; ++i) {
			int maximum = Integer.MIN_VALUE;
			Task taskWithMaximumID = null;
			for (Task t : originalList) {
				if (t.getID() >= maximum) {
					maximum = t.getID();
					taskWithMaximumID = t;
				}
			}
			sortedList.add(taskWithMaximumID);
			originalList.remove(taskWithMaximumID);
		}
		return sortedList;
	}

	private List<Task> reverse(List<Task> originalList) {
		List<Task> reversedList = new ArrayList<Task>();
		for (int i = originalList.size() - 1; i >= 0; --i) {
			reversedList.add(originalList.get(i));
		}
		return reversedList;
	}

	@Override
	public void longPress(final int taskID) {
		CharSequence[] options = { "Delete", "Rename" };
		final AlertDialog newTabDialog = new AlertDialog.Builder(getActivity())
				.setItems(options, new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (which == 0) {
							deleteTask(taskID);
						} else if (which == 1) {
							renameTask(taskID);
						}
					}
				}).show();
		// newTabDialog.getWindow().setSoftInputMode(
		// WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

	}

	public void uncheckAllTasks() {
		for (Task t : mTasks) {
			t.setCompleted(false);
			mDataPersistence.persistTask(t);
		}
		mTaskListAdapter.notifyDataSetChanged();
	}

	protected void renameTask(final int taskID) {
		// Toast.makeText(mContext, "here!", Toast.LENGTH_SHORT).show();
		Task task = getTaskWithID(taskID);
		final EditText taskNameEditText = new EditText(getActivity());
		String taskName = task.getName();
		taskNameEditText.setText(taskName);
		taskNameEditText.setSelection(taskName.length());
		final AlertDialog newTabDialog = new AlertDialog.Builder(getActivity())
				.setTitle("Rename an Item")
				// .setMessage("Current name: " + task.getName())
				.setView(taskNameEditText)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int ignored) {
						renameTask(taskID, taskNameEditText.getText()
								.toString());
					}

				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int ignored) {
								// TODO Auto-generated method stub

							}
						}).show();
		newTabDialog.getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

	}
}
